package com.itheima.service.impl;

import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberMapper memberMapper;

    /**
     * 手机验证码登录
     * @param telephone
     * @param validateCode
     * @return
     */
    @Override
    public boolean loginByValidateCode(String telephone, String validateCode) {
        //从redis中获取验证码
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String validateCode0 = new String();
        try {
            validateCode0 = (String)valueOperations.get(telephone);
        } catch (Exception e) {
            return false;
        }
        //手机号错误或者是验证码没了
        if(validateCode0 == null){
            return false;
        }
        //验证码正确,成功登录
        if(validateCode0.equals(validateCode)){
            //判断是否注册过并进行相应的操作
            List<Member> list = memberMapper.getMemberByTelephone(telephone);
            //不存在 则注册
            if(list == null || list.size() == 0){
                Member member = new Member();
                member.setPhoneNumber(telephone);
                memberMapper.addMember(member,LocalDate.now());
            }
            return true;
        }
        //验证码错误,登陆失败
        else return false;
    }
}
